<?PHP
class myan_OAuth_Information{
public $PROVIDER = null;
public $OAUTH_DIV_ID = null;
public $PROVIDER_ICON_LOCATION = null;
private $whereToReturnOnSuccess = null;

public function __construct($provider, $whereToReturnOnSuccess=null) {
	$this->PROVIDER = $provider;
	if( $whereToReturnOnSuccess == null)
		$this->whereToReturnOnSuccess = "document.location.href";
	else
		$this->whereToReturnOnSuccess = "'$whereToReturnOnSuccess'";
		
	$GOOGLE_LOGOUT_URL = "https://www.google.com/accounts/Logout";
	
	if( $this->PROVIDER == 'google')
	{
		$this->PROVIDER_ICON_LOCATION = '//buetian-dot-com-theme-wordpress.googlecode.com/svn/Trunk/buetian4.0/images/google_signin.png';
	}
	else if( $this->PROVIDER == 'facebook')
	{
		$this->PROVIDER_ICON_LOCATION = '//buetian-dot-com-theme-wordpress.googlecode.com/svn/Trunk/buetian4.0/images/fblogin.png';
	}
	else
		throw new Exception("Invalid provider: $provider");
	$this->OAUTH_DIV_ID = "OAUTH_CONNECT_".rand();
}

public function js_connect_info(){
	if($this->PROVIDER == 'google')
		$this->js_connect_info_google();
	else
		$this->js_connect_info_facebook();
}
private function js_connect_info_facebook(){
?>
<script type='text/javascript'>
(function(){
	var FACEBOOK_CLIENT_ID = "<?PHP echo get_option("facebook_oauth_appid_value", "220636254729676"); ?>";

	document.getElementById("<?PHP echo $this->OAUTH_DIV_ID;?>").onclick = function() {
		// adding a global variable to mark facebook option is taken
		var req = {
			"authUrl" : "https://www.facebook.com/dialog/oauth",
			"clientId" : FACEBOOK_CLIENT_ID,
			"redirectURI" : "<?PHP bloginfo("wpurl");?>/wp-admin/admin-ajax.php?action=myan_goauth_login" //If necessary this url must end with '/'
		};
		var loginUrl= req.authUrl+'?response_type=token&client_id='+req.clientId;
		//loginUrl += '&scope='+req.scopes.join(' ');
		loginUrl += '&state=facebook_'+encodeURIComponent(encodeURIComponent(<?PHP echo $this->whereToReturnOnSuccess; ?>));
		loginUrl += '&redirect_uri='+encodeURIComponent(req.redirectURI);
		
		window.location = loginUrl;
	}
})();
</script>	
<?PHP	
}
private function js_connect_info_google(){
?>
<script type='text/javascript'>
(function(){
	var GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/auth";
	var GOOGLE_CLIENT_ID = "<?PHP echo get_option("gplus_oauth_appid_value", "846969533537-tie2r85mm5267gid458l4p3qv97b75nk.apps.googleusercontent.com"); ?>";
	var PLUS_ME_SCOPE = "https://www.googleapis.com/auth/plus.me";

	document.getElementById("<?PHP echo $this->OAUTH_DIV_ID;?>").onclick = function() {
		// adding a global variable to mark google option is taken
		if( window.googleProvider == null)
			googleProvider = true;
		else
		{
			alert("Cannot set oauth provider more than once");
			return;
		}
		var req = {
		"authUrl" : GOOGLE_AUTH_URL,
		"clientId" : GOOGLE_CLIENT_ID,
		"scopes" : [ PLUS_ME_SCOPE ], //"scopes" : [ PLUS_ME_SCOPE, PLUS_ANOTHER_SCOPE ]
		"redirectURI" : "<?PHP bloginfo("wpurl");?>/wp-admin/admin-ajax.php?action=myan_goauth_login" //If necessary this url must end with '/'
		};
		var loginUrl= req.authUrl+'?response_type=token&client_id='+req.clientId;
		loginUrl += '&scope='+req.scopes.join(' ');
		loginUrl += '&state=google_'+encodeURIComponent(encodeURIComponent(<?PHP echo $this->whereToReturnOnSuccess; ?>));
		loginUrl += '&redirect_uri='+encodeURIComponent(req.redirectURI);
		
		window.location = loginUrl;
	}
})();
</script>
<?PHP
}

public function php_generic_validateToken($token){
	if($this->PROVIDER == 'google')
		return $this->php_validateToken_google($token);
	else if($this->PROVIDER == 'facebook')
		return $this->php_validateToken_facebook($token);
}

private function php_validateToken_google($token){
	$apiurl = "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=" . $token;
	$jsonContent = @file_get_contents($apiurl);
	if($jsonContent == null)
		throw new Exception("Unable to connect to Google server. Please check your server log.");
	$data = json_decode($jsonContent);
	
	if($data->error)
		throw new Exception($data->error);
		
	if( $data->audience == get_option('gplus_oauth_appid_value') )
	{
		$apiurl = "https://www.googleapis.com/plus/v1/people/{$data->user_id}?fields=image%2Cname%2Curl&access_token=$token";
		$jsonContent = @file_get_contents($apiurl);
		$dataFromApi = json_decode($jsonContent);
		
		$userDataFromServer = new stdClass();
		$userDataFromServer->id = $data->user_id;
		$userDataFromServer->displayName = $dataFromApi->name->givenName.' '.$dataFromApi->name->familyName;
		
		$userDataFromServer->link = $dataFromApi->url;
		$url_with_querystring = $dataFromApi->image->url;
		$url_data = parse_url($url_with_querystring);
		$userDataFromServer->profile_pic = str_replace('?'.$url_data['query'], '', $url_with_querystring);
		
		return $userDataFromServer;
	}	
	throw new Exception("Given token is not issued for this application");
}
private function php_validateToken_facebook($token){
	$apiurl = "https://graph.facebook.com/v2.1/me?fields=id,name,cover,link,picture.width(9000).height(9000)&access_token=" . $token;
	$jsonContent = @file_get_contents($apiurl);
	if($jsonContent == null)
		throw new Exception("Unable to connect to Facebook server. Please check your server log.");
		
	$data = json_decode($jsonContent);
	if( $data == false)
		throw new Exception("Invalid token or unable to connect to Facebook server. Please check your server log.");
	
	if($data->id == null)
		throw new Exception("Cannot find any user id with the provided access_token");

	$userDataFromServer = new stdClass();
	$userDataFromServer->id = $data->id;
	$userDataFromServer->displayName = $data->name;
	$userDataFromServer->profile_pic = $data->picture->data->url;
	$userDataFromServer->link = $data->link;
	
	return $userDataFromServer;
}

public function renderHtmlButton(){
?>
<div id="<?PHP echo $this->OAUTH_DIV_ID;?>" style="">
	<img style="height: 25px;width: 150px;cursor: pointer;" src="<?PHP echo $this->PROVIDER_ICON_LOCATION; ?>" />
</div>
<?PHP
}

}
?>